package com.common.libhttp.upload;


import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Description:
 * Company:
 * Email:bjxm2013@163.com
 * Created by Devin Sun on 2017/4/3.
 */
public class UploadHelper {

    private Call call;

    public static final String MULTIPART_FORM_DATA_IMAGE = "image/jpg";       // 指明要上传的文件格式
    public static final String MULTIPART_FORM_DATA_FILE = "multipart/form-data";       // 指明要上传的文件格式
    private String MULTIPART_FORM_DATA = MULTIPART_FORM_DATA_FILE;


    public void uploadFile(String url, String filePath, Map<String, String> map,String tag, final UploadListener uploadListener) {
        File file = new File(filePath);             // 需要上传的文件
        String filename = file.getName().substring(0, file.getName().length() - 4);
        RequestBody requestFile =               // 根据文件格式封装文件
                RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);

        // 初始化请求体对象，设置Content-Type以及文件数据流
        MultipartBody.Builder requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)            // multipart/form-data
                .addFormDataPart("file", file.getName(), requestFile);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            requestBody.addFormDataPart(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
        }


        // 封装OkHttp请求对象，初始化请求参数
        Request request = new Request.Builder()
                .url(url)                // 上传url地址
                .post(requestBody.build())              // post请求体
//                .addHeader("token", AppDataManager.getInstance().getUser().getToken())//添加token
                .tag(tag)
                .build();

        call = initClient(uploadListener).newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (uploadListener != null) {
                    uploadListener.onSuccess(call, response);
                }

            }

            @Override
            public void onFailure(Call call, IOException e) {
                if (uploadListener != null) {
                    uploadListener.onFailure(call, e);
                }
            }
        });

//        Observable.just(call)
//                .subscribeOn(Schedulers.io())
//                .observeOn(Schedulers.io())
//                .subscribe(new Consumer<Call>() {
//                    @Override
//                    public void accept(@NonNull Call call) throws Exception {
//                        Response response = call.execute();
//
//                        if (!response.isSuccessful()) {
//                            throw new IOException("Unexpected code " + response);
//                        } else {
//                            FileUtils.saveFile(dirPath, fileName, response.body().byteStream());
//                            response.close();
//
//                            if (uploadListener != null) {
//                                Observable.just(new File(dirPath, fileName)).subscribeOn(Schedulers.io())
//                                        .observeOn(AndroidSchedulers.mainThread())
//                                        .subscribe(new Consumer<File>() {
//                                            @Override
//                                            public void accept(@NonNull File file) throws Exception {
//                                                uploadListener.onSuccess(file);
//                                            }
//                                        });
//                            }
//                        }
//                    }
//
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(@NonNull Throwable throwable) {
//                        Observable.just(throwable).subscribeOn(Schedulers.io())
//                                .observeOn(AndroidSchedulers.mainThread())
//                                .subscribe(new Consumer<Throwable>() {
//                                    @Override
//                                    public void accept(@NonNull Throwable throwable) throws Exception {
//                                        if (uploadListener != null) {
//                                            uploadListener.onFailure(throwable);
//                                        }
//                                    }
//                                });
//                    }
//                });

    }


    public void cancelDownload() {
        if (call != null && !call.isCanceled()) {
            call.cancel();
        }
    }

    private OkHttpClient initClient(final UploadListener uploadListener) {

        return new OkHttpClient.Builder().
                addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder().addHeader("Accept-Encoding", "identity").build();
                        return chain.proceed(request);
                    }
                }).addInterceptor(new UpLoadProgressInterceptor(uploadListener)).build();
    }
}
